<template>
  <div v-loading="loading" class="order-manage-main">
    <div class="top-container">
      <!-- tab start -->
      <div class="type-tab-container">
        <el-tabs v-model="filterForm.type" @tab-click="search(1)">
          <!-- <el-tab-pane label="快递物流订单" name="EXPRESS" />
          <el-tab-pane label="即时配送订单" name="LOCAL" />
          <el-tab-pane label="到店自提订单" name="SELF_PICKUP" />-->
          <el-tab-pane label="全部订单" name="all" />
          <!--          <el-tab-pane label="虚拟方案订单" name="VIRTUAL" />-->
          <!--          <el-tab-pane label="快递物流订单" name="EXPRESS" />-->
          <!--          <el-tab-pane label="同城配送订单" name="LOCAL" />-->
          <!--          <el-tab-pane label="到店自提订单" name="SELF_PICKUP" />-->
        </el-tabs>
      </div>
      <!-- tab end -->

      <!-- 筛选条件 start -->
      <div class="filter-container">
        <el-form ref="filterForm" :model="filterForm" :rules="rules" inline label-width="120px" size="small">
          <el-form-item
            :class="
              filterForm.orderNo || filterForm.sourceName ? '' : 'is-required'
            "
            prop="createDate"
            label="下单时间："
          >
            <el-date-picker
              v-model="filterForm.createDate"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="~"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item prop="chargeOffTime" label="核销时间：">
            <el-date-picker
              v-model="filterForm.chargeOffTime"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="~"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item prop="phone" label="下单号码：">
            <el-input v-model.trim="filterForm.downPhone" maxlength="20" />
          </el-form-item>
          <el-form-item prop="downPhone" label="预约号码：">
            <el-input v-model.trim="filterForm.phone" maxlength="20" />
          </el-form-item>
          <el-form-item prop="sourceName" label="资源名称：">
            <el-input v-model="filterForm.sourceName" clearable maxlength="50" />
          </el-form-item>
          <el-form-item prop="orderNo" label="订单编号：">
            <el-input v-model="filterForm.orderNo" maxlength="50" />
          </el-form-item>
          <el-form-item prop="storeId" label="下单门店：">
            <el-select v-model="filterForm.storeId" filterable placeholder="可通过名称搜索" style="width: 400px">
              <el-option label="全部门店" value />
              <el-option v-for="(item, index) in shopOptions" :key="index" :label="item.name" :value="item.shopId" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式：" prop="paymentMethod">
            <el-select v-model="filterForm.paymentMethod" placeholder="支付方式" class="w-400">
              <el-option label="所有方式" value="" />
              <el-option v-for="(key, value) in PAYMENT_METHOD" :key="value" :label="key" :value="Number(value)" />
            </el-select>
          </el-form-item>
          <el-form-item label="下单方式：" prop="paymentType">
            <el-select v-model="filterForm.paymentType" placeholder="下单方式" class="w-400">
              <el-option label="所有方式" value="all" />
              <el-option
                v-for="(key, value) in RESERVATION_PAY_TYPE_TEXT"
                :key="value"
                :label="key"
                :value="Number(value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="withRemarks" label="商家备注：">
            <el-select v-model="filterForm.withRemarks" filterable clearable placeholder="" style="width: 400px">
              <el-option value="all" label="全部" />
              <el-option :value="1" label="已备注" />
              <el-option :value="2" label="未备注" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="status" label="订单状态：">
            <el-select
              v-model.number="filterForm.status"
              placeholder="所有方式"
              style="width: 400px"
            >
              <el-option label="全部状态" value="all" />
              <el-option
                v-for="key in RESERVATION_ORDER_STATE_TEXT"
                :key="key"
                :label="key"
                :value="key"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item prop="status" label="活动批次：">
            <el-input
              v-model="filterForm.activityBatch"
              clearable
              maxlength="50"
            /> 这一期没有
          </el-form-item> -->
          <div>
            <el-form-item label=" ">
              <el-button type="primary" round @click="search(1)">查 询
              </el-button>
              <el-button round @click="reset">重 置 </el-button>
              <el-button round @click="downExcel">导出 </el-button>
              <!--<el-button-->
              <!--  type="text"-->
              <!--  round-->
              <!--  @click="isShowMoreFilter=!isShowMoreFilter">{{ isShowMoreFilter ? '隐藏' : '展开' }}高级选项-->
              <!--</el-button>-->
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 筛选条件 end -->
    </div>

    <!-- 表格 start -->
    <div class="table-container app-main-content-box">
      <!-- 方案状态tab start -->
      <div class="status-tab-container">
        <el-tabs v-model="filterForm.status" @tab-click="search(1)">
          <el-tab-pane label="全部状态" name="all" />
          <el-tab-pane v-for="(v, k) in statusOptions" :key="k" :label="v" :name="v" />
        </el-tabs>
      </div>
      <!-- 方案状态tab end -->

      <!-- 列表 start-->
      <el-table :data="list" :span-method="arraySpanMethod" style="width: 100%">
        <el-table-column prop="orderNo" label="方案" width="220">
          <template slot-scope="scope">
            <!-- 单 -->
            <div v-if="scope.$index % 2 == 0" class="flexRBS">
              <div>
                <span style="margin-right:20px">
                  订单编号：
                  <span class="app-text-color-primary">{{
                    scope.row.orderNo
                  }}</span> </span>
                <span style="margin-right:20px">下单时间：{{ scope.row.createTime }}</span>
                <span
                  v-if="
                    scope.row.subStatus === 'FINISH' ||
                      scope.row.subStatus === 'CANCEL'
                  "
                >完成时间：{{ scope.row.updateTime }}</span>
                <span v-if="scope.row.name" style="margin-right:20px">预约人：{{ scope.row.name }}</span>
                <span v-if="scope.row.phone" style="margin-right:20px">预约电话：{{ scope.row.phone }}</span>
                <span v-if="scope.row.time" style="margin-right:20px">预约时间：{{ scope.row.time }}</span>
                <span v-if="scope.row.categoryVOS.length" style="margin-right:20px">预约资源：<span
                  v-for="(item, index) in scope.row.categoryVOS"
                  :key="index"
                >
                  <i v-if="item.categoryName">
                    {{ item.categoryName }}
                  </i>
                  <i v-if="item.categoryLevelName">（{{ item.categoryLevelName }}）</i>
                </span></span>
                <!-- 双 -->
                <!-- <ul>
                  <li
                    v-for="(item, index) in scope.row.categoryVOS"
                    :key="index"
                    class="common-row-start-box"
                  >
                    <span
                      class="app-line-two"
                    >{{ item.categoryName }} * {{ item.categoryLevelName }}</span>
                  </li>
                </ul> -->
              </div>
              <div style="color: rgb(245, 108, 108)">
                商家备注： {{ scope.row.remark || '无' }}
              </div>
              <div style="color: rgb(245, 108, 108)">
                顾客备注： {{ scope.row.customerRemark || '无' }}
              </div>
            </div>
            <!-- 双 -->
            <ul v-else>
              <li v-for="(item, index) in scope.row.goodsVOList" :key="index" class="common-row-start-box">
                <div class="cover-img">
                  <img v-if="item.coverImg" :src="fileBaseUrl + item.coverImg" alt srcset>
                </div>
                <div class="goods-title app-line-two">
                  <span v-if="item.goodsType === 101" class="app-text-color-primary">【搭配】</span>{{ item.title }}
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="goodAllSku" label="SKU">
          <template slot-scope="scope">
            <div class="common-row-start-box">
              {{ scope.row.goodAllSku }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="单价/数量">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <div>￥{{ scope.row.categoryTotalPrice / 100 }} × {{ scope.row.categoryNum || 1 }}</div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="tradeFee" label="应付">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <div>
                  <div>￥{{ scope.row.orderVo.totalFee / 100 }}</div>
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="tradeFee" label="支付方式">
          <template slot-scope="scope">
            <ul v-if="scope.row.paymentMethod">
              <li class="common-row-start-box">
                <div>
                  <el-tag :type="paymentTagMap[scope.row.paymentMethod]">{{ PAYMENT_METHOD[scope.row.paymentMethod] }}
                  </el-tag>
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="tradeFee" label="下单方式">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <div>
                  <el-tag type="info">{{ RESERVATION_PAY_TYPE_TEXT[scope.row.paymentType] }}
                  </el-tag>
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <!-- <div>{{statusOptions[scope.row.subStatus]}}</div> -->
                <el-tag :type="TAG_MAP[scope.row.status]">{{ RESERVATION_ORDER_STATE_TEXT[scope.row.status] }}
                </el-tag>
              </li>
            </ul>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <div>
              <el-button type="text" icon="el-icon-setting" @click="handleOrder(scope.row.orderNo)">订单管理</el-button>
              <el-button type="text" icon="el-icon-printer" @click="putSealTicket(scope.row.orderNo)">打印小票</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total !== 0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
      <!-- 列表 end -->
    </div>
    <!-- 表格 end -->

    <!-- 组件 -->

    <HandleOrder ref="handleOrder" />
    <!-- <DialogSku /> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { storeList } from '@/views/wxaMallModule/api/shop'
import HandleOrder from './components/HandleOrder'
import { downMallOrdersList } from '@/api/reservation'
import {
  getReservationOrderList,
  printReservationOrder
} from '@/api/reservation'
import {
  RESERVATION_ORDER_STATE_TEXT,
  RESERVATION_PAY_TYPE_TEXT,
  TAG_MAP,
  PAYMENT_METHOD,
  paymentTagMap
} from '@/views/wxaReservationModule/views/orderManage/constant'

export default {
  components: {
    HandleOrder
    // DialogSku,
  },
  data() {
    const validatorDate = (rule, value, callback) => {
      if (
        this.filterForm.orderNo ||
        this.filterForm.sourceName ||
        (value && value.length)
      ) {
        callback()
      } else {
        callback(new Error('请选择时间'))
      }
    }
    return {
      // 配置
      rules: {
        createDate: [
          {
            validator: validatorDate,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      shopOptions: [],
      statusOptions: RESERVATION_ORDER_STATE_TEXT,
      RESERVATION_ORDER_STATE_TEXT,
      RESERVATION_PAY_TYPE_TEXT,
      PAYMENT_METHOD,
      subTypeOptions: {
        DEFAULT: '常规销售',
        DEPOSIT_PRESELL: '定金预售',
        FULL_PRESELL: '全款预售',
        PRESELL: '预售',
        SEC_KILL: '秒杀',
        GROUP: '拼团'
      },
      // 状态
      shopOptionsLoaded: false,
      isShowMoreFilter: true,
      loading: false,
      lastPaymentMethodsArr: [], // 上一次选择
      filterForm: {
        createDate: [
          this.$momentMini().subtract(6, 'days').format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        orderNo: '',
        sourceName: '',
        phone: '',
        downPhone: '',
        type: 'all',
        subType: '',
        storeId: '',
        status: 'all',
        subStatus: 'all',
        withRemarks: 'all',
        paymentMethod: '',
        paymentType: 'all'
      },
      list: [],
      TAG_MAP,
      paymentTagMap
    }
  },
  computed: {
    ...mapGetters([
      'fileBaseUrl',
      'paymentOptions',
      'paymentKeyOptions',
      'userShopId'
    ]),
    msgGetOrderNo() {
      return this.$store.state.message.msgGetOrderNo
    }
  },
  watch: {
    msgGetOrderNo() {
      this.openMsgOrderInfo()
    },
    'filterForm.status'() {
      this.filterForm.subStatus = 'all'
    },
    'filterForm.sourceName'() {
      this.$refs.filterForm.validateField(['createDate'])
    },
    'filterForm.orderNo'() {
      this.$refs.filterForm.validateField(['createDate'])
    }
  },
  mounted() {
    if (this.$route.query.sourceName && this.$route.query.subType) {
      this.filterForm.createDate = []
      this.filterForm.sourceName = this.$route.query.sourceName
      this.filterForm.subType = this.$route.query.subType
    }
    if (this.$route.query.orderNo) {
      this.filterForm.createDate = []
      this.filterForm.orderNo = this.$route.query.orderNo
      this.handleOrder(this.$route.query.orderNo)
    }
    this.fetchData()
    // 订单消息跳转过来后弹窗
    this.openMsgOrderInfo()
    // this.$router.push({ query: {} })
    const arrFrom = ['invoice','cancelTable']
    this.$route.query.orderNo && arrFrom.indexOf(this.$route.query.from) > -1 && this.openOrderDetail({ orderNo: this.$route.query.orderNo })
  },
  methods: {
    openMsgOrderInfo() {
      const { orderNo, path } = this.msgGetOrderNo
      const isCan = this.$route.path === path
      console.log(this.$route.path, path)
      if (orderNo && isCan) {
        this.handleOrder(orderNo)
        this.$store.dispatch('SetMsgOrderNo', {})
      }
    },
    // 打印小票
    putSealTicket(orderNo) {
      printReservationOrder({ orderNo }).then((res) => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '打印成功',
            type: 'success'
          })
        }
      })
    },
    /**
     * 数据组
     */
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(async(valid) => {
        if (valid) {
          if (!this.shopOptionsLoaded) await this.getShopOptions()
          this.filterForm.pageNum = pageNum
          this.filterForm.pageSize = pageSize
          const params = this.fetchFilterParams()
          this.loading = true
          getReservationOrderList(params)
            .then((res) => {
              const list = []
              res.data.list.forEach((v) => {
                list.push(v, v)
              })
              this.list = list
              this.paginationConfig.total = res.data.total
              this.paginationConfig.page = res.data.pageNum
            })
            .finally(() => {
              this.loading = false
            })

          //
        }
      })
    },

    fetchFilterParams() {
      const params = Object.assign({}, this.filterForm)
      if (params.createDate && !params.orderNo) {
        params.downOrderStartTime = params.createDate[0]
        params.downOrderEndTime = params.createDate[1]
      }
      params.chargeOffTime && !params.orderNo && (params.useOrderStartTime = params.chargeOffTime[0], params.useOrderEndTime = params.chargeOffTime[1])
      params.status && (params.status = this.findKeyByValue(this.RESERVATION_ORDER_STATE_TEXT, params.status) * 1)

      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      delete params.createDate
      delete params.chargeOffTime
      !params.status && delete params.status
      // TODO 暂时解决门店id权限问题 不是总部强制查询当前门店id
      if (this.userShopId !== 0) {
        params.storeId = this.shopOptions[0].storeId
      }
      return params
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 获取门店列表
    getShopOptions() {
      return new Promise((resolve, reject) => {
        storeList()
          .then((res) => {
            this.shopOptionsLoaded = true
            let shopList = []
            res.data.some((v) => {
              if (v.storeId === this.userShopId) {
                shopList = [v]
                return true
              } else {
                shopList.push(v)
              }
            })
            this.shopOptions = shopList
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    /**
     * 按钮组
     */
    // 查询
    search() {
      this.fetchData(1)
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
    },

    // 导出
    downExcel() {
      const data = this.fetchFilterParams()
      downMallOrdersList(data).then((res) => {
        if (res.code === 0) {
          this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
            confirmButtonText: '确定',
            center: true,
            type: 'success'
          })
        }
      })
    },

    //  订单打印
    handlePrint(orderNo) {
      // this.$refs.handleOrder.open({ orderNo }).then((res) => {
      // })
    },

    //  订单管理
    handleOrder(orderNo) {
      this.$refs.handleOrder.open({ orderNo }).then((res) => {
        this.fetchData()
      })
    },

    /**
     * 方法组
     */
    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2 == 0) {
        return [1, 10]
      }
    },
    // 通过对象通过value找key仅适用第一层value为基本数据类型
    findKeyByValue(obj, value) {
      for (const key in obj) {
        if (obj[key] === value) {
          return key
        }
      }
      return ''
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.order-manage-main {
  ::v-deep {
    .el-tabs__header {
      margin-bottom: 0;
      background-color: #fff;
      border-radius: 0 0 5px 5px;
    }

    .el-tabs__item {
      font-weight: bold;
    }

    .el-tabs__active-bar {
      height: 4px;
    }
  }

  .el-input,
  .el-select {
    width: 400px;
  }
}

/* 头部 */
.top-container {
  padding: 24px 30px 0;
  border-radius: 5px;
  background-color: #fff;
}

/* 筛选 */
.filter-container {
  margin: 20px 0 10px;
}

/* 表格 */
.table-container {
  margin-top: 10px;

  ::v-deep {
    .el-table tr:nth-of-type(odd) td {
      border: none;
    }

    .el-table__row {
      td:not(:first-child) {
        vertical-align: top;
      }
    }

    .el-table td {
      border-bottom: 1px solid #dcdfe6;
      font-weight: bold;
    }
  }
}

/* 状态筛选 */
.status-tab-container {
  margin-bottom: 10px;
}

/* 表格内部通用盒子 */
.common-row-start-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;
  margin-bottom: 12px;

  .cover-img {
    margin-right: 10px;
    flex: 0 0 50px;
    height: 50px;
    border: 1px solid #e7e7e7;
  }

  .goods-title {
    font-weight: bold;
    color: #000;
  }
}

.common-column-start-box {
  display: flex;
  justify-content: center;
  flex-direction: column;
  height: 50px;
  margin-bottom: 12px;
}

i {
  font-style: normal;
}

.flexRBS {
  display: flex;
  flex-direction: column;
}
</style>
